import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		user: null,
	    token: '',
	},
	mutations: {
		// login(state, user) {
		// 	state.user = user
		// 	// 缓存用户信息
		// 	Vue.prototype.$cache.set('_user', user, 0)
		// },
		// logout(state) {
		// 	state.user = null
		// 	// 清理缓存用户信息
		// 	Vue.prototype.$cache.delete('_user')
		// }
		SET_TOKEN: (state, token) => {
		  state.token = token
		},
		SET_USER: (state, user) => {
		  state.user = user
		},
		SET_ROLES: (state, roles) => {
		  state.roles = roles
		},
		SET_PERMISSION_GRANTS: (state, permissionGrants) => {
		  state.permissionGrants = permissionGrants
		}
	},
	actions: {
		login({
			commit
		}, params) {
			return new Promise((resolve, reject) => {
				 //  api请求
				 Vue.prototype.$minApi.login(params).then(res => {
					 commit('SET_TOKEN', res.access_token)
					 resolve(res)
				 }).catch(err => {
					 reject(err)
				 })
				
			})
		},
		logout({
			commit
		}) {
			commit('SET_TOKEN', '')
			commit('SET_USER', null)
		},
		getInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				 //  api请求
				 Vue.prototype.$minApi.getInfo().then(res => {
					 const data = res

					 const user = {
						 id: data.id,
						 name: data.name,
						 avatar: data.avatar,
						 phone: data.phoneNumber
					 }
					 commit('SET_USER', user)
					 resolve(res)
				 }).catch(err => {
					 reject(err)
				 })
				
			})
		}
	},
	getters: {
		user: state => {
			if (state.user) {
				return state.user
			}
			return null
		},
		token: state => {
			if (state.token) {
				return state.token
			}
			return null
		}
	}
})

export default store
